/* eslint-disable no-unused-vars */
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { Skill } from '@/types/skill'

// 用户状态
export interface SkillState {
  storeSkills: Skill[]
  addSkill: (skill: Skill | null) => Skill | null
  addSkills: (skills: Skill[]) => Skill[]
  contains: (skill: Skill) => boolean
  clear: () => void
}

// 创建一个自定义的存储，带有过期逻辑
const createExpiringStorage = (storage: Storage, expireIn: number) => {
  return {
    getItem: (name: string) => {
      const item = storage.getItem(name)
      if (!item) return null

      const { value, expiry } = JSON.parse(item)
      if (Date.now() > expiry) {
        storage.removeItem(name)
        return null
      }
      return value
    },
    setItem: (name: string, value: unknown) => {
      const expiry = Date.now() + expireIn
      const item = JSON.stringify({ value, expiry })
      storage.setItem(name, item)
    },
    removeItem: (name: string) => {
      storage.removeItem(name)
    }
  }
}

// 检查 localStorage 是否可用
const isLocalStorageAvailable = () => {
  try {
    const testKey = '__test__'
    localStorage.setItem(testKey, testKey)
    localStorage.removeItem(testKey)
    return true
  } catch (e) {
    return false
  }
}

// 创建技能
export const battleskillStore = create<SkillState>()(
  persist(
    (set, get) => ({
      storeSkills: [],
      addSkill: (skill: Skill | null) => {
        if (skill && !get().storeSkills.some((s) => s.id === skill.id)) {
          set((state) => ({
            storeSkills: [...state.storeSkills, skill]
          }))
          return skill
        }
        return null
      },
      addSkills: (skills: Skill[]) => {
        const newSkills = skills.filter(
          (skill) => !get().storeSkills.some((s) => s.id === skill.id)
        )
        set((state) => ({
          storeSkills: [...state.storeSkills, ...newSkills]
        }))
        return newSkills
      },
      contains: (skill: Skill) => {
        return get().storeSkills.some((s) => s.id === skill.id)
      },
      clear: () => {
        set({ storeSkills: [] })
      }
    }),
    {
      name: 'battle_skill_v3',
      storage: isLocalStorageAvailable()
        ? createExpiringStorage(localStorage, 1 * 60 * 60 * 1000)
        : undefined
      // storage: createJSONStorage(localStorage),
    }
  )
)
